<template>
  <div class="container">
    <el-row>
      <!-- 状态码占比 -->
      <el-col style="text-align: right">
        <label for="">ES索引名</label>
        <el-select v-model="listQuery[0].indexName" size="small" class="w-140">
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label for="">状态码</label>
        <el-select v-model="listQuery[0].status" size="small" class="w-140">
          <el-option
            v-for="item in options2"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <date-range-picker
          v-model="datePicker[0]"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="search(0)"
        >搜索</el-button
        >
      </el-col>
    </el-row>
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activaNameArr[0]" type="card">
          <el-tab-pane label="状态码占比" name="first">
            <div class="echart">
              <div
                id="echartsOne"
                :style="{ width: '100%', height: '680px' }"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
    <div
      class="dividing-line"
      style="margin: 10px 0; border: 1px solid #e6e6e6"
    />
    <!-- 响应时长占比 -->
    <el-row>
      <el-col style="text-align: right">
        <label for="">ES索引名</label>
        <el-select v-model="listQuery[1].indexName" size="small" class="w-140">
          <el-option
            v-for="item in options1"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <label for="">响应时长</label>
        <el-select
          v-model="listQuery[1].responseTimeIndex"
          size="small"
          class="w-140"
        >
          <el-option
            v-for="item in options3"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <date-range-picker
          v-model="datePicker[1]"
          type="daterange"
          align="right"
          size="small"
          class="w-240"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
        />
        <el-button
          type="primary"
          icon="el-icon-search"
          size="small"
          @click="search(1)"
        >搜索</el-button
        >
      </el-col>
    </el-row>
    <el-row class="p-t-15">
      <el-col>
        <el-tabs ref="tabs" v-model="activaNameArr[1]" type="card">
          <el-tab-pane label="响应时长占比" name="first">
            <div class="echart">
              <div
                id="echartsTwo"
                :style="{ width: '100%', height: '680px' }"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import echarts from 'echarts';
import { dateShortcutKeyJS } from '@/mixins/index.js';
import timeUtils from '@/utils/timeHandle.js';
import {
  getIndexAndStatusApi,
  getErrStatusListApI,
  getRequestTimeListApi
} from '@/api/online-quality.js';
const domMap = {
  0: 'echartsOne',
  1: 'echartsTwo'
};
export default {
  mixins: [dateShortcutKeyJS],
  data() {
    return {
      domMap,
      options1: [], // ES索引名
      options2: [], // 状态码
      options3: [], // 响应时长
      datePicker: [
        [
          timeUtils.timeHandle(
            new Date(new Date().getTime() - 7 * 24 * 3600000).getTime(),
            'date'
          ),
          timeUtils.timeHandle(new Date().getTime() - 1 * 24 * 3600000, 'date')
        ],
        [
          timeUtils.timeHandle(
            new Date(new Date().getTime() - 7 * 24 * 3600000).getTime(),
            'date'
          ),
          timeUtils.timeHandle(new Date().getTime() - 1 * 24 * 3600000, 'date')
        ]
      ],
      activaNameArr: ['first', 'first'],
      listQuery: [
        {
          indexName: null,
          status: null,
          startTime: null,
          endTime: null
        },
        {
          indexName: null,
          responseTimeIndex: null,
          startTime: null,
          endTime: null
        }
      ],
      list: [{}, {}],
      legend: [[], []] // 接口返回的ES索引名
    };
  },

  mounted() {
    this.getOption();
  },

  methods: {
    async getOption() {
      try {
        const {
          code,
          data: { indexList, statusList, timeList }
        } = await getIndexAndStatusApi();

        if (code == 200) {
          const option1 = [];
          const option2 = [];
          const option3 = [];

          indexList.forEach((item) => {
            const obj = {
              value: item.value,
              label: item.name
            };
            option1.push(obj);
          });
          statusList.forEach((item) => {
            const obj = {
              value: item.value,
              label: item.name
            };
            option2.push(obj);
          });
          timeList.forEach((item) => {
            const obj = {
              value: item.value,
              label: item.name
            };
            option3.push(obj);
          });

          this.options1 = option1;
          this.options2 = option2;
          this.options3 = option3;

          this.listQuery[0].indexName = indexList[0].value;
          this.listQuery[1].indexName = indexList[0].value;
          this.listQuery[0].status = statusList[0].value;
          this.listQuery[1].responseTimeIndex = timeList[0].value;

          this.search(0);
          this.search(1);
        } else {
          this.$message.error('请求出错了');
        }
      } catch (e) {
        console.log(e);
      }
    },

    search(index) {
      const listQuery = this.listQuery[index];
      const datePicker = this.datePicker[index];

      if (!datePicker) {
        this.$message.warning('请输入搜索时间', true);
        return;
      }

      listQuery.startTime = datePicker[0];
      listQuery.endTime = datePicker[1];
      this.listQuery[index] = listQuery;

      this.getData(index);
    },

    getLegendAndseries(obj) {},

    async getData(index) {
      const { domMap, listQuery } = this;
      var myChart = echarts.init(document.getElementById(domMap[index]));
      myChart.showLoading();
      try {
        const query = { ...listQuery[index] };
        const { code, data } =
          index == 0
            ? await getErrStatusListApI(query)
            : await getRequestTimeListApi(query);
        if (code == 200) {
          const legend = [];
          const dataMap = {};
          Object.keys(data).forEach((key) => {
            legend.push(key);
            dataMap[key] = [];
          });

          this.legend[index] = legend;
          const list = { ...dataMap };
          const obj = { ...dataMap };
          let date = [];
          Object.keys(list).forEach((key) => {
            obj[key] = (data && data[key]) || [];
          });

          Object.keys(obj).forEach((key) => {
            const objItem = obj[key];
            const dataArr = [];
            const totalArr = [];
            const hitCountArr = [];
            const percentArr = [];
            for (let i = 0; i < objItem.length; i++) {
              const item = objItem[i];
              dataArr.push(item.date);
              totalArr.push(item.total);
              hitCountArr.push(item.hitCount);
              percentArr.push(item.percent);
            }
            list[key].total = totalArr;
            list[key].hitCount = hitCountArr;
            list[key].percent = percentArr;
            date = dataArr;
          });

          this.list[index] = { ...list, date };
          this.upDateEchart(index);
        } else {
          myChart.hideLoading();
        }
      } catch (err) {
        myChart.hideLoading();
      }
    },

    upDateEchart(index) {
      const { domMap, legend, list } = this;
      const currentLegend = legend[index];
      const currentList = list[index];

      var myChart = echarts.init(document.getElementById(domMap[index]));
      myChart.showLoading();

      const option1 = {
        color: this.$store.state.app.eChartColor,

        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: ['当前项', '总数', '占比']
        },
        grid: {
          left: 100,
          right: 100
        },
        xAxis: [
          {
            type: 'category',
            data: currentList.date,
            axisPointer: {
              type: 'shadow'
            }
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '占比',
            min: 0,
            max: Math.ceil(Math.max(...currentList[currentLegend[0]].percent)),
            interval: Math.ceil(
              Math.max(...currentList[currentLegend[0]].percent) / 5
            ),
            axisLabel: {
              formatter: '{value} %'
            }
          },
          {
            type: 'value',
            name: '请求量',
            min: 0,
            max: Math.ceil(Math.max(...currentList[currentLegend[0]].total)),
            interval: Math.ceil(
              Math.max(...currentList[currentLegend[0]].total) / 5
            ),
            axisLabel: {
              formatter: '{value}'
            }
          }
        ],
        series: [
          {
            name: '当前项',
            type: 'bar',
            yAxisIndex: 1,
            data: currentList[currentLegend[0]].hitCount
          },
          {
            name: '总数',
            type: 'bar',
            yAxisIndex: 1,
            data: currentList[currentLegend[0]].total
          },
          {
            name: '占比',
            type: 'line',
            yAxisIndex: 0,
            data: currentList[currentLegend[0]].percent
          }
        ]
      };

      const series = [];
      let maxPercent = 0;
      currentLegend.forEach((item, idx) => {
        const obj = {
          name: currentLegend[idx],
          type: 'line',
          data: currentList[currentLegend[idx]].percent
        };
        maxPercent = Math.max(maxPercent, Math.max(...currentList[currentLegend[idx]].percent));
        series.push(obj);
      });

      const option2 = {
        color: this.$store.state.app.eChartColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            crossStyle: {
              color: '#999'
            }
          }
        },
        legend: {
          data: legend[index]
        },
        grid: {
          left: 60,
          right: 60,
          top: 120
        },
        xAxis: [
          {
            type: 'category',
            data: currentList.date
          }
        ],
        yAxis: [
          {
            type: 'value',
            name: '占比',
            min: 0,
            max: Math.ceil(maxPercent),
            interval: Math.ceil(maxPercent / 5),
            position: 'left',
            axisLabel: {
              formatter: '{value} %'
            }
          }
        ],
        series: series
      };

      const option = currentLegend.length > 1 ? option2 : option1;
      myChart.setOption(option, true);
      myChart.hideLoading();
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  margin: 15px;
  .p-t-15 {
    padding-top: 15px;
  }
}
</style>
